package com.sky.controller.admin;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.GiteeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Map;


@RestController
@RequestMapping("/admin/common")
@Api(tags="通用接口")
@Slf4j
public class CommonController {

    /**
     *  上传图片
     * @param file 文件对象
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> uploadImg(MultipartFile file) throws IOException {
        log.info("uploadImg()请求已来临...");
        String originalFilename = file.getOriginalFilename();
        String targetURL = GiteeUtil.createUploadFileUrl(originalFilename);
        log.info("目标url：" + targetURL);

        // 封装请求体
        Map<String, Object> uploadBodyMap = GiteeUtil.getUploadBodyMap(file.getBytes());
        // 将请求体转换为 JSON 格式的字符串
        String jsonRequestBody = new ObjectMapper().writeValueAsString(uploadBodyMap);

        // 使用 Apache HttpClient 发送 POST 请求
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(targetURL);
            httpPost.setEntity(new StringEntity(jsonRequestBody, ContentType.APPLICATION_JSON));

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String JSONResult = EntityUtils.toString(response.getEntity());
                // 使用 Jackson 或 Gson 解析 JSON
                JsonNode jsonObj = new ObjectMapper().readTree(JSONResult);

                // 请求失败处理
                if (jsonObj == null || jsonObj.get("commit") == null) {
                    return Result.error(MessageConstant.UPLOAD_FAILED);
                }

                log.info("响应data为：" + jsonObj.get("content").get("download_url").asText());
                // 请求成功：返回下载地址
                return Result.success(jsonObj.get("content").get("download_url").asText());
            }
        }
    }
}